CREATE PROCEDURE RRHH_REGISTRAR_ACTIVIDAD_L
@@IDEMPLEADO INTEGER,
@FECHA DATETIME,
@HORAINICIO DATETIME,
@HORAFIN DATETIME,
@ACTIVIDAD VARCHAR(200),
@ESTADOTRAN INTEGER OUTPUT
AS

--SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRANSACTION

DECLARE @IDAC INTEGER
DECLARE @CONT INTEGER
DECLARE @FECAUX DATETIME

BEGIN TRY
	--comprobamos si ya esta registrado ese dia
	SET @CONT = (SELECT COUNT(*) FROM AGENDADIARIA
				 WHERE CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
				 @IDEMPLEADO = idEmpleado)
				 
	IF @CONT = 0
	BEGIN
		INSERT INTO AGENDADIARIA (fecha, idEmpleado)
		VALUES (@FECHA, @IDEMPLEADO)
	END
	--ELSE
	--BEGIN
		--comprobamos que no exista ya una actividad o que hallan cruces
	SET @CONT = (SELECT COUNT(*) FROM AGENDAACTIVIDAD
				 WHERE idEmpleado = @IDEMPLEADO AND CAST(fecha AS DATE) = CAST(@FECHA AS DATE) 
				 AND
				 (
				 ((CAST(@HORAINICIO AS TIME(7)) >= CAST(horaInicioAct AS TIME(7)))
				 AND (CAST(@HORAINICIO AS TIME(7)) <= CAST(horaFinActividad AS TIME(7))) 
				 AND (CAST(@HORAFIN AS TIME(7)) >= CAST(horaInicioAct AS TIME(7))) 
				 AND (CAST(@HORAFIN AS TIME(7)) <= CAST(horaFinActividad AS TIME(7))))
				 OR
				 ((CAST(@HORAINICIO AS TIME(7)) > CAST(horaInicioAct AS TIME(7))) 
				 AND (CAST(@HORAINICIO AS TIME(7)) < CAST(horaFinActividad AS TIME(7))) 
				 AND (CAST(@HORAFIN AS TIME(7)) > CAST(horaFinActividad AS TIME(7))))
		       	 OR
				 ((CAST(@HORAINICIO AS TIME(7)) < CAST(horaInicioAct AS TIME(7))) 
				 AND (CAST(@HORAFIN AS TIME(7)) > CAST(horaInicioAct AS TIME(7)))
				 AND (CAST(@HORAFIN AS TIME(7)) < CAST(horaFinActividad AS TIME(7))))
				 OR
				 ((CAST(@HORAINICIO AS TIME(7)) < CAST(horaInicioAct AS TIME(7))) 
				 AND (CAST(@HORAFIN AS TIME(7)) > CAST(horaFinActividad AS TIME(7)))) 
				 )
				 AND ESTADO = 1
				 )	
		  		 
	IF @CONT = 0
	BEGIN
		--obtenemos el maximo id de la actividad de ese dia
		SET @IDAC = (SELECT MAX(IDAGENDAACTIVIDAD) FROM AGENDAACTIVIDAD
					WHERE idEmpleado = @IDEMPLEADO AND CAST(FECHA AS DATE) = CAST(@FECHA AS DATE)) 
			
		IF (@IDAC IS NULL)
		BEGIN
			SET @IDAC = 1
		END
		ELSE
		BEGIN
			SET @IDAC = @IDAC + 1
		END		
		
		SET @FECAUX = (SELECT FECHA FROM AGENDADIARIA 
		               WHERE CAST(FECHA AS DATE) = CAST(@FECHA AS DATE) AND
		               IDEMPLEADO = @IDEMPLEADO)
		               
		--registramos la nueva actividad
		INSERT INTO AGENDAACTIVIDAD (idAgendaActividad, fecha, idEmpleado, horaInicioAct,
		horaFinActividad, actividad, idLineaPedidoVentaServicio, estado) VALUES (@IDAC, @FECAUX,
		@IDEMPLEADO, @HORAINICIO, @HORAFIN, @ACTIVIDAD, NULL, 1)
			
		SET @ESTADOTRAN = 1
		
		--COMMIT TRANSACTION
	END
	ELSE
	BEGIN
		SET @ESTADOTRAN = 3
		
		--COMMIT TRANSACTION
	END

	COMMIT TRANSACTION
	--END
END TRY
BEGIN CATCH
	SET @ESTADOTRAN = 0
	ROLLBACK TRANSACTION
END CATCH